<template>
  <div class="btn-single-upload-image">
    <el-upload
        class="btn-single-upload-image-upload"
      :action="uploadFileUrl"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :show-file-list="false"
      :headers="headers"
    >
      <slot>
        <el-button icon="el-icon-plus" size="mini" type="primary">上传</el-button>
      </slot>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        <template v-if="tip">
          {{tip}}
        </template>
        <template v-else>
          请上传
          <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
          的文件
        </template>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    tip: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      imageUrl: '',
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/infra/file/upload",
      headers: { Authorization: "Bearer " + getToken() },
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.imageUrl = val
        } else {
          this.imageUrl = ''
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log({ name: res.data.url, url: res.data.url })
      console.log('文本图片',URL.createObjectURL(file.raw))
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data.url;
      this.$emit("input", this.imageUrl);
      this.$modal.closeLoading();
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
  }
};
</script>
<style scoped lang="scss">
.btn-single-upload-image {
  width: 100%;
  .btn-single-upload-image-upload {
    display: flex;
    justify-content: center;
    align-items: center;
    .el-upload {
      width: 100% !important;
    }
  }
}
</style>

